//
//  DetailViewController.swift
//  VO_Yuejie
//
//  Created by laichunhui on 15/11/26.
//  Copyright © 2015年 lch. All rights reserved.
//

import UIKit
import SVProgressHUD


class DetailViewController: UICollectionViewController {
    
    // 主题视图
    var topicViewModel : TopicViewModel
    
    // page视图列表
    lazy var listViewModel = PageListViewModel()

//MARK: - 生命周期
    
    // MARK: 构造函数
    init(topicVM: TopicViewModel) {
        let layout = UICollectionViewFlowLayout()

        layout.minimumLineSpacing = 0
        
        topicViewModel = topicVM
        
        super.init(collectionViewLayout: layout)
     
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
       // setupCollectionView
        setupCollectionView()
        
        collectionView?.mj_header.beginRefreshing()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    private func setupCollectionView() {
        
        self.automaticallyAdjustsScrollViewInsets = false
        
        // 下拉刷新控件
        collectionView!.mj_header = MyRefreshHeader(refreshingTarget: self, refreshingAction: "loadPageData")
        // bg
        let bg = UIImageView(image: UIImage(named: "sm_timeline_default_bg"))
        bg.frame = ScreenBounds
        collectionView?.backgroundView = bg
        
        // 注册cell
        collectionView!.registerNib(UINib(nibName: "PageCell", bundle: nil), forCellWithReuseIdentifier: pageCellRID)
        
        // 注册headerView
        collectionView?.registerClass(PageHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView")
        
        // 注册footerView
        collectionView?.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterView")
        
    }
    
    func loadPageData() {
        
        listViewModel.loadTopicDetail(topicViewModel.topic.value!) { (error) -> () in
            
            self.collectionView?.mj_header.endRefreshing()
            
            print(self.listViewModel.pages)
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网路不给力")
                return
            }
            self.collectionView?.reloadData()
        }
    }
}

// MARK:- UICollectionViewDataSource
extension DetailViewController {
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return listViewModel.pages.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // 1. 取出视图模型
        let vm = listViewModel.pages[indexPath.row]
        
        // 2. 获取可重用 cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pageCellRID, forIndexPath: indexPath) as! PageCell
        
        // 3. 设置视图模型
        cell.viewModel = vm
        
        cell.indexLabel.text = indexPath.row < 9 ? "0" + "\(indexPath.row + 1)" : "\(indexPath.row + 1)"
        
       // cell.contentView.backgroundColor = cell.selected ? UIColor.grayColor() : UIColor.cyanColor()
        return cell
    }
    
    // 设置headerView和footerView
    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        
        var reusableView = UICollectionReusableView()
        
        if kind == UICollectionElementKindSectionHeader {
            
            let headerView: PageHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", forIndexPath: indexPath) as! PageHeaderView

            headerView.viewModel = topicViewModel
    
            reusableView = headerView
        }
        
        if kind == UICollectionElementKindSectionFooter {
            
            let footerview: UICollectionReusableView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterView", forIndexPath: indexPath)
            footerview.backgroundColor = UIColor.whiteColor()
            
            let button = UIButton(type: .Custom)
            footerview.addSubview(button)
            
            button.snp_makeConstraints(closure: { (make) -> Void in
                make.top.equalTo(footerview).offset(5)
                make.bottom.equalTo(footerview).offset(-5)
                make.width.equalTo(60)
                make.height.equalTo(20)
                make.centerX.equalTo(footerview)
            })
            button.setTitle("关于版权", forState: .Normal)
            button.titleLabel?.textAlignment = NSTextAlignment.Left
            button.titleLabel?.font = UIFont.systemFontOfSize(12)
            button.setTitleColor(UIColor.colorWith(113, green: 113, blue: 113, alpha: 1), forState: .Normal)
            reusableView = footerview
        }
        
        return reusableView
    }

}
    
// MARK:- UICollectionViewDelegate
extension DetailViewController {
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    }
    
    override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    
    }
    
}

extension DetailViewController: UICollectionViewDelegateFlowLayout {
    // headerSize
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSizeMake(ScreenWidth, topicViewModel.headerViewHeight)
    }

    // footerSize
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

        return CGSizeMake(ScreenWidth, 30)
    }
    
    // itemSize
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        let vm = listViewModel.pages[indexPath.row]

        return CGSizeMake(ScreenWidth, vm.rowHeight)
    }
    
}